from django.db import models
from django.contrib.auth import get_user_model
from apps.books.models import Book

User = get_user_model()


class Order(models.Model):
    """订单主表"""
    ORDER_STATUS_CHOICES = [
        ('pending', '待付款'),
        ('paid', '已付款'),
        ('processing', '处理中'),
        ('shipped', '已发货'),
        ('delivered', '已送达'),
        ('cancelled', '已取消'),
        ('refunded', '已退款'),
    ]

    PAYMENT_METHOD_CHOICES = [
        ('alipay', '支付宝'),
        ('wechat', '微信支付'),
        ('card', '银行卡'),
        ('balance', '余额支付'),
    ]

    order_number = models.CharField(max_length=32, unique=True, verbose_name='订单号')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders')
    status = models.CharField(max_length=20, choices=ORDER_STATUS_CHOICES, default='pending', verbose_name='订单状态')
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD_CHOICES, blank=True, verbose_name='支付方式')
    
    # 金额信息
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='订单总金额')
    discount_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='优惠金额')
    shipping_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='运费')
    final_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='实付金额')
    
    # 收货信息
    shipping_name = models.CharField(max_length=100, verbose_name='收货人姓名')
    shipping_phone = models.CharField(max_length=20, verbose_name='收货人电话')
    shipping_address = models.TextField(verbose_name='收货地址')
    shipping_zip = models.CharField(max_length=10, blank=True, verbose_name='邮政编码')
    
    # 物流信息
    tracking_number = models.CharField(max_length=100, blank=True, verbose_name='物流单号')
    logistics_company = models.CharField(max_length=100, blank=True, verbose_name='物流公司')
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True)
    paid_at = models.DateTimeField(null=True, blank=True, verbose_name='付款时间')
    shipped_at = models.DateTimeField(null=True, blank=True, verbose_name='发货时间')
    delivered_at = models.DateTimeField(null=True, blank=True, verbose_name='送达时间')
    cancelled_at = models.DateTimeField(null=True, blank=True, verbose_name='取消时间')
    
    # 备注信息
    user_note = models.TextField(blank=True, verbose_name='用户备注')
    admin_note = models.TextField(blank=True, verbose_name='管理员备注')
    
    # 退款信息
    refund_reason = models.TextField(blank=True, verbose_name='退款原因')
    refund_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='退款金额')
    refund_status = models.CharField(max_length=20, choices=[
        ('none', '无退款'),
        ('requested', '申请退款'),
        ('approved', '退款已批准'),
        ('completed', '退款完成'),
        ('rejected', '退款拒绝'),
    ], default='none', verbose_name='退款状态')

    class Meta:
        db_table = 'orders'
        verbose_name = '订单'
        verbose_name_plural = '订单'
        ordering = ['-created_at']

    def __str__(self):
        return self.order_number


class OrderItem(models.Model):
    """订单明细"""
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='order_items')
    quantity = models.PositiveIntegerField(verbose_name='购买数量')
    unit_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='单价')
    discount_price = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='优惠单价')
    total_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='小计金额')

    class Meta:
        db_table = 'order_items'
        verbose_name = '订单明细'
        verbose_name_plural = '订单明细'

    def __str__(self):
        return f"{self.order.order_number} - {self.book.title}"


class OrderLog(models.Model):
    """订单操作日志"""
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='logs')
    action = models.CharField(max_length=50, verbose_name='操作类型')
    description = models.TextField(verbose_name='操作描述')
    operator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'order_logs'
        verbose_name = '订单日志'
        verbose_name_plural = '订单日志'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.order.order_number} - {self.action}"


class ShoppingCart(models.Model):
    """购物车"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cart_items')
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='cart_items')
    quantity = models.PositiveIntegerField(default=1, verbose_name='数量')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'shopping_cart'
        verbose_name = '购物车'
        verbose_name_plural = '购物车'
        unique_together = ['user', 'book']
        ordering = ['-updated_at']

    def __str__(self):
        return f"{self.user.email} - {self.book.title}"
